package com.bee.bootstrap.role.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bee.bootstrap.plugs.shiro.JwtRealm;
import com.bee.bootstrap.resource.entity.Resource;
import com.bee.bootstrap.resource.service.IResourceService;
import com.bee.bootstrap.role.entity.Role;
import com.bee.bootstrap.role.mapper.RoleMapper;
import com.bee.bootstrap.role.service.IRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bee.bootstrap.roleResource.entity.RoleResource;
import com.bee.bootstrap.roleResource.service.IRoleResourceService;
import com.bee.bootstrap.user.entity.User;
import com.bee.bootstrap.user.service.IUserService;
import com.bee.common.core.enums.StatusEnum;
import com.bee.common.core.result.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liekkas
 * @since 2018-05-25
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private IRoleResourceService roleResourceServiceImpl;
    @Autowired
    private IResourceService resourceServiceImpl;
    @Autowired
    private JwtRealm jwtRealm;
    @Autowired
    private IUserService userServiceImpl;

    @Override
    public Result findPageView(Page<Role> page, Role role) {
        EntityWrapper<Role> entityWrapper = new EntityWrapper(role);
        if(StringUtils.isNotBlank(role.getRoleQuery())){
            entityWrapper.like("role",role.getRoleQuery());
        }
        if(StringUtils.isNotBlank(role.getCodeQuery())){
            entityWrapper.like("code",role.getCodeQuery());
        }
        return Result.success(this.selectPage(page,entityWrapper));
    }

    @Override
    public Result deleteRoleById(long id) {
        Role role=this.selectById(id);
        role.setStatus(StatusEnum.INVALID.toString());
        this.updateById(role);
        return Result.success("删除成功");
    }

    @Override
    public Result updateRole(Role role) {
        if(!this.persistenceAble(role)){
            return Result.fail("角色编码重复");
        }
        role.setUpdateTime(new Date());
        return Result.success("修改成功",this.updateById(role));
    }

    @Override
    public Result insertRole(Role role) {
        if(!this.persistenceAble(role)){
            return Result.fail("角色编码重复");
        }
        role.setStatus(StatusEnum.NORMAL.toString());
        role.setCreateTime(new Date());
        return Result.success("保存成功",this.insert(role));
    }

    @Override
    public List<Role> findRolesByCodes(Set<String> roleCodes) {
        return this.selectList(new EntityWrapper<Role>().in("code",roleCodes).eq("status",StatusEnum.NORMAL.toString()));
    }

    @Override
    public Result findRoleResources(long id) {
        List<RoleResource> roleResources=roleResourceServiceImpl.findResourcesByRoleId(id);
        List<Long> resourcesId=new ArrayList<>();
        if(roleResources!=null&&roleResources.size()>0){
            roleResources.forEach(roleResource -> {
                resourcesId.add(roleResource.getResourceId());
            });
        }
        List<Resource> resources=resourceServiceImpl.selectList(new EntityWrapper<Resource>().in("id",resourcesId));
        if(resources!=null&&resources.size()>0){
            resources.forEach(resource -> {
                roleResources.forEach(roleResource -> {
                    if(roleResource.getResourceId().compareTo(resource.getId())==0){
                        resource.setPermissionLevel(roleResource.getPermissionLevel());
                    }
                });
            });
        }
        return resourcesId.size()>0?Result.success(resources):Result.success(Arrays.asList());
    }

    @Override
    public Result addRoleResources(long roleId, Role role) {
        if(role.getRoleResources()!=null&&role.getRoleResources().size()>0){
            roleResourceServiceImpl.deleteResourceByRoleId(roleId);
            roleResourceServiceImpl.createRoleResources(roleId,role.getRoleResources());
            //清除用户资源缓存
            List<User> users=userServiceImpl.findUsersByRoleId(roleId);
            if(users!=null&&users.size()>0){
               for(User user:users){
                   jwtRealm.clearCache(user.getToken());
               }
            }
        }
        return Result.success("角色资源保存成功");
    }

    private boolean persistenceAble(Role role){
        Role persistence=this.selectOne(new EntityWrapper<Role>()
                .eq("code",role.getCode()));
        return persistence==null||role.getId().compareTo(persistence.getId())==0;
    }
}
